using System;
using System.Collections;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
using Sedna.Core.Controller;
using Sedna.Core.Controller.Configurations;
using Sedna.Core.Controls.Support;
using Sedna.Core.Controls.Support.Javascript;
using Sedna.Core.DataBinding;
using Sedna.Core.Tiles.Contents;
using DataBinder = Sedna.Core.DataBinding.DataBinder;

namespace Sedna.Core.Controls
{
	public class RadioButton : System.Web.UI.WebControls.RadioButton, IContent, IConfigurationAware,  ILabelledControl,
		IClientScriptingControl, IControlDataLoadAware
	{
		private IConfiguration configuration;
		private string configurationId = "configuration.default.RadioButton";
		private string textKey;
		
		protected IDataBinder binder;

		private bool clientScriptingEnabled=false;
		private string clientVariable=null;

		private String contentPlaceHolderId;

        private string javascriptClass;

        public string LocalizedText
        {
            get
            {
                if (Configuration.DataTranslator != null && Configuration.DataTranslator.GetType() != typeof(TrivialDataTranslator))
                {
                    return Text;
                }
                return Configuration.GetLocalizedPostfixLabel(TextKey, Text);
            }
        }

        #region Properties

        public String ContentPlaceHolderId
		{
			get { return contentPlaceHolderId;}
			set { contentPlaceHolderId = value;}
		}

		public IConfiguration Configuration
		{
			get { return configuration; }
			set { this.configuration = value; }
		}

		[Bindable(true), Category("Sedna"), DefaultValue("configuration.default.RadioButton")]
		public string ConfigurationId
		{
			get { return configurationId; }
			set { this.configurationId = value; }
		}
	
		public string TextKey
		{
			get { return textKey; }
			set { textKey = value; }
		}

	    public bool ClientScriptingEnabled
	    {
	        get { return clientScriptingEnabled /*|| clientVariable != null*/; }
	        set { clientScriptingEnabled = value; }
	    }

	    public string ClientVariable
	    {
            get { return /*clientVariable*/ ControlUtil.GetClientVariable(this, clientVariable); }
	        set { clientVariable = value; }
	    }

	    private string UniqueGroupName
		{
			get 
			{
				string uniqueGroupName = this.GroupName;
				int lastColonIndex = UniqueID.LastIndexOf('$');
				if (lastColonIndex >= 0)
				{
					uniqueGroupName = UniqueID.Substring(0, lastColonIndex + 1) + uniqueGroupName;
				}
				return uniqueGroupName;
			}
        }

        #endregion

        #region Javascript support

        public string JavascriptClass
        {
            get { return javascriptClass; }
            set { javascriptClass = value; }
        }

        public string NodeName
        {
            get { return ClientID; }
        }


        #endregion


	    
        public RadioButton()
			:base()
		{
			this.CssClass = "radio";
		}

		public RadioButton(string id, string textKey, string text )
			:this()
		{
			this.ID = id;
			this.TextKey = textKey;
			this.Text = text;
		}

		public RadioButton(IConfiguration configuration): this()
		{
			this.configuration = configuration;
			this.configurationId = configuration.ObjectName;
//			this.ID = configuration.Id;
			BuildControlFromConfiguration();
		}

		protected override void OnInit(EventArgs e)
		{
			if (configuration == null) 
			{
				configuration = (IConfiguration)SpringContextFactory.GetContext().GetObject(configurationId);
                Build();
			}
		    
			ControlUtil.SetupClientAttributes(this, configuration);
//			ControlUtil.SetupValidators(this, configuration);			

			binder=new DataBinder(this, configuration, ExecutionContext.GetCurrent(ClientID));
			base.OnInit (e);
		}

		protected void BuildControlFromConfiguration()
		{
			this.ID = configuration.Id;
			this.TextKey = configuration.TextKey;

			IRadioButtonConfiguration radioButtonConfiguration=Configuration as IRadioButtonConfiguration;
		    
			if (radioButtonConfiguration==null)
			{
				return;	
			}

			ClientScriptingEnabled=radioButtonConfiguration.ClientScriptingEnabled;
			ClientVariable=radioButtonConfiguration.ClientVariable;
			GroupName=radioButtonConfiguration.GroupName;	
			Checked=radioButtonConfiguration.Checked;
            AutoPostBack = radioButtonConfiguration.AutoPostBack;

            Build();
		}		

		protected void Build()
		{
            this.Visible = configuration.Visible && configuration.IsVisibleForPrincipal();
            this.Enabled = configuration.Enabled && configuration.IsEnabledForPrincipal();
		}

		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);
			IDictionary executionContext=ExecutionContext.GetCurrent(ClientID);
			Unbind();
			ControlUtil.ExecuteOnLoad(executionContext, Context, Configuration, this.ClientID);

            if (Configuration.VisibleBindPath != null)
                this.Visible = true; // To reach the OnPreRender method and analyze visibility in the Bind method
		}

		public void OnDataLoad()
		{
			IDictionary executionContext=ExecutionContext.GetCurrent(ClientID);
			ControlUtil.ExecuteOnDataLoad(executionContext, Context, Configuration, this.ClientID);
		}

		protected override void OnPreRender(EventArgs e)
		{
			IDictionary executionContext=ExecutionContext.GetCurrent(ClientID);
			ControlUtil.ExecuteOnPreRender(executionContext, Context, Configuration, this.ClientID);
			Bind();
			if (ClientScriptingEnabled)
			{
				EnableClientScripting();
			}
			base.OnPreRender(e);

            Text = LocalizedText;
		}

		private void EnableClientScripting()
		{
            JavascriptController controller = JavascriptController.Current;

			controller.DeclareClass("RadioGroup");
            controller.DeclareObjectWithQuotedParams(ClientVariable, "RadioGroup", UniqueGroupName, GetSubmitState());
		}

		private string GetSubmitState()
		{
			System.Web.UI.WebControls.RadioButton checkedRadioButton=GetCheckedRadioButton(NamingContainer);
			if(checkedRadioButton!=null)
			{
				return checkedRadioButton.ID;
			}
			return String.Empty;
		}


		private System.Web.UI.WebControls.RadioButton GetCheckedRadioButton(Control parent)
		{
			foreach (Control control in parent.Controls)
			{
				System.Web.UI.WebControls.RadioButton radioButton=control as System.Web.UI.WebControls.RadioButton;
				if (radioButton!=null&&radioButton.Checked)
				{
					return radioButton;
				}
				if (!(control is INamingContainer))
				{
					radioButton=GetCheckedRadioButton(control);
					if (radioButton!=null)
					{
						return radioButton;
					}
				}
			}
			return null;
		}

		private void Bind()
		{
            this.Visible = this.configuration.Visible;		    		    
		    
			binder.Bind(new string[]{"Text", "TextKey", "Enabled", "Checked", "Visible"});

            Enabled = Enabled && configuration.IsEnabledForPrincipal();
            Visible = Visible && configuration.IsVisibleForPrincipal();
		    
			Text=Configuration.GetLocalizedPostfixLabel(TextKey, Text);
		}

		private void Unbind()
		{
            binder.Unbind(new string[] { "Text", "TextKey", "Enabled", "Checked", "Visible"});	
		}


	}
}
